package cn.tom.config.customize;

import cn.tom.tools.XResp;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 酒辞
 * // 登录失败
 */
@Component
@Slf4j
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        log.info("登录失败");
        response.setStatus(401); //HTTP 状态码 401 未登录
        response.setContentType("application/json;charset=utf8");
        Map<String,Object>map=new HashMap<>();
        map.put("code",401);
        map.put("msg",exception.getMessage());
        map.put("token","");
        ObjectMapper objectMapper=new ObjectMapper();
        String json=objectMapper.writeValueAsString(map);
        response.getWriter().println(json);
        response.flushBuffer();
    }
}
